<?php

namespace backend\controllers;

use Yii;
use yii\filters\AccessControl;
use backend\models\BackendController;
use yii\filters\VerbFilter;
use yii\web\UploadedFile;

/**
 * Site controller
 */
class UploadController extends BackendController {

    private $tmpPath;
    private $tmpUrl;

    public function init() {
        parent::init();
        $this->tmpPath = Yii::getAlias('@temp');
        $this->tmpUrl = Yii::$app->params['urls']['temp'];

        $this->clear();
    }

    /**
     * @inheritdoc
     */
    public function behaviors() {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'actions' => ['login', 'error', 'frame', 'page'],
                        'allow' => true,
                    ],
                    [
                        'actions' => ['temp', 'kindeditor', 'attr-img'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'logout' => ['post'],
                ],
            ],
        ];
    }

    /**
     * @inheritdoc
     */
    public function actions() {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
        ];
    }

    public function actionTemp() {
        $allowExt = ['jpg', 'jpeg', 'png', 'gif'];
        $maxFileSize = 819200;  //800K

        $temp = UploadedFile::getInstanceByName('tempFile');
        if ($temp) {
            $ext = strtolower($temp->getExtension());

            if (!in_array($ext, $allowExt)) {
                $this->renderJSON(['error_msg' => '不允许上传的文件类型！'], false);
            }

            if ($temp->size > $maxFileSize) {
                $this->renderJSON(['error_msg' => '文件大小超出范围！'], false);
            }

            $path = uniqid() . '.' . $ext;
            $temp->saveAs($this->tmpPath . '/' . $path);

            $ret = [
                'path' => $path,
                'url' => $this->tmpUrl . $path,
            ];
            $this->renderJSON($ret);
        } else {
            $this->renderJSON(['error_msg' => '上传文件错误！'], false);
        }
    }

    public function actionKindeditor() {
        $allowExt = ['jpg', 'jpeg', 'png', 'gif'];
        $maxFileSize = 1048576;  //1M

        $temp = UploadedFile::getInstanceByName('imgFile');
        if ($temp) {
            $ext = strtolower($temp->getExtension());

            if (!in_array($ext, $allowExt)) {
                $this->json(['error' => 1, 'message' => '不允许上传的文件类型！']);
            }

            if ($temp->size > $maxFileSize) {
                $this->json(['error' => 1, 'message' => '文件大小超出范围！']);
            }

            $path = uniqid() . '.' . $ext;
            $temp->saveAs($this->tmpPath . '/' . $path);

            $ret = [
                'error' => 0,
                'url' => $this->tmpUrl . $path,
            ];

            $this->json($ret);
        } else {
            $this->renderJSON(['error_msg' => '上传文件错误！'], false);
        }
    }

    /**
     * 上传商品属性图片
     */
    public function actionAttrImg() {
        $allowExt = ['jpg', 'jpeg', 'png', 'gif'];
        $maxFileSize = 1048576;  //1M

        $post = Yii::$app->request->post();
        $id = $post['id'];

        $temp = UploadedFile::getInstanceByName('img');
        if ($temp) {
            $ext = strtolower($temp->getExtension());

            if (!in_array($ext, $allowExt)) {
                $this->js('alert("不允许上传的文件类型！");');
            }

            if ($temp->size > $maxFileSize) {
                $this->js('alert("文件大小超出范围！");');
            }

            $path = uniqid() . '.' . $ext;
            $temp->saveAs($this->tmpPath . '/' . $path);

            $url = $this->tmpUrl . $path;
            $this->js("parent.setAttrImgUrl('{$id}','{$url}','{$path}');");
        } else {
            $this->js('alert("上传文件错误！");');
        }
    }

    private function clear() {
        $key = 'tempClearTime';
        $cacheTime = Yii::$app->cache->get($key);

        if (!$cacheTime || $cacheTime < time() - 24 * 60 * 60) {
            $outTime = strtotime(date("Y-m-d 00:00:00", strtotime("-1 day")));
            if ($dh = opendir($this->tmpPath)) {
                while (( $file = readdir($dh)) !== false) {
                    if ($file != "." && $file != "..") {
                        $path = $this->tmpPath . '/' . $file;
                        filectime($path) < $outTime && @unlink($path);
                    }
                }
                closedir($dh);
            }
            Yii::$app->cache->set($key, time());
        }
    }

}
